<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ title }}
      <div class="goback" @click="$router.replace(`/options/homePageList`)">
        <i class="el-icon-refresh-left" /> {{ translate("backPage") }}
      </div>
    </div>
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <el-form-item :label="translate('adverTypes')" prop="type">
        <el-select
          v-model="param.type"
          clearable
          style="width: 400px"
          :placeholder="translate('adverTypesPlace')"
          @change="deleteDeviceConfigAddImage"
        >
          <el-option
            v-for="item in adTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="translate('adverTitle')" prop="title">
        <el-input
          v-model="param.title"
          type="text"
          style="width: 400px"
          :placeholder="translate('titlePlace')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="translate('adverPic')" prop="imageFullPath">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="KNOWLEDGE_IMG"
            :fixed-number="
              param.type == '4'
                ? [1000, 1334]
                : param.type == '5'
                ? [910, 768]
                : param.type == '2'
                ? [80, 80]
                : [690, 300]
            "
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="flex-c">
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            accept=".jpg,.png"
            :data="uploadData"
            :show-file-list="false"
            :on-change="addFileChange"
            :on-success="uploadSuccess"
            :auto-upload="true"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="param.imageFullPath"
              class="file"
              :style="'background-image: url(' + param.imageFullPath + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholder9 ml10">
            <div>
              {{ translate("jycc") }}：{{
                param.type == "4"
                  ? "1000px X 1334px"
                  : param.type == "5"
                  ? "910px, 768px"
                  : param.type == "2"
                  ? "80px X 80px"
                  : "690px X 300px"
              }}
            </div>
            <div>
              {{ translate("zctpsm") }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="translate('gllx')" prop="configId">
        <el-select
          v-model="param.configId"
          style="width: 400px"
          :placeholder="translate('gllxP')"
          @change="selectType"
        >
          <el-option
            v-for="item in types"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          (param.type != '4' &&
            (param.configId == 5 ||
              param.configId == 2 ||
              param.configId == 8 ||
              param.configId == 3 ||
              param.configId == 7)) ||
          (param.type == '4' &&
            (param.configId == 2 || param.configId == 8 || param.configId == 3))
        "
        :label="translate('applyVenue')"
        prop="venueIds"
      >
        <el-select
          v-model="param.venueIds"
          multiple
          clearable
          style="width: 400px"
          :placeholder="translate('applyVenueP')"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          param.configId &&
          param.configId != 5 &&
          param.configId != 2 &&
          param.configId != 3 &&
          param.configId != 8 &&
          param.configId != 11 &&
          param.configId != 7
        "
        :label="translate('applyVenue')"
        prop="venueIds"
      >
        <el-select
          v-model="param.venueIds"
          :multiple-limit="1"
          multiple
          clearable
          style="width: 400px"
          :placeholder="translate('applyVenueP')"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          param.configId &&
          param.configId != 5 &&
          param.configId != 7 &&
          param.configId != 11 &&
          param.configId != 8
        "
        :label="translate('glnr')"
        prop="aboutIndex"
      >
        <el-select
          v-model="param.aboutIndex"
          style="width: 400px"
          :placeholder="translate('glnrP')"
          @change="selectContent"
        >
          <el-option
            v-for="(item, index) in activeList"
            :key="index"
            :label="item[activeName] || item.name"
            :value="index"
          />
        </el-select>
      </el-form-item>
      <!-- 视频号 -->
      <template v-if="param.configId == '7'">
        <el-form-item :label="translate('videoNumId')" prop="videoNumberId">
          <el-input
            v-model="param.videoNumberId"
            style="width: 400px"
            :placeholder="translate('videoNumIdP')"
          />
        </el-form-item>
        <el-form-item style="margin-top: -20px">
          <div class="placeholder9">
            <span>{{ translate("videoNumIdDesc") }}</span>
            <a
              href="https://channels.weixin.qq.com/"
              target="_blank"
              class="primaryColor underline"
              >{{ translate("videoNumHelp") }}</a
            >
            <span>，{{ translate("copyVideoNumId") }}</span>
          </div>
          <div>
            <el-image
              class="w400"
              :preview-src-list="[
                'https://axure-file.lanhuapp.com/md5__6d903ccf499fd6042fd1a332091bdbfd.png',
              ]"
              src="https://axure-file.lanhuapp.com/md5__6d903ccf499fd6042fd1a332091bdbfd.png"
            />
          </div>
        </el-form-item>
        <el-form-item :label="translate('videoId')" prop="videoId">
          <el-input
            v-model="param.videoId"
            style="width: 400px"
            :placeholder="translate('videoIdP')"
          />
        </el-form-item>
        <el-form-item style="margin-top: -20px">
          <div class="placeholder9">
            <span>{{ translate("videoIdDesc") }}</span>
            <a
              href="https://channels.weixin.qq.com/"
              target="_blank"
              class="primaryColor underline"
              >{{ translate("videoNumHelp") }}</a
            >
            <span>，{{ translate("copyVideoId") }}</span>
          </div>
          <div>
            <el-image
              class="w400"
              :preview-src-list="[
                'https://axure-file.lanhuapp.com/md5__fe942d7dc67e783dd04aeb849577af58.png',
              ]"
              src="https://axure-file.lanhuapp.com/md5__fe942d7dc67e783dd04aeb849577af58.png"
            />
          </div>
        </el-form-item>
      </template>
      <!-- 专项卡 -->
      <template v-if="param.configId == '8'">
        <el-form-item :label="translate('placechooseSCard')" prop="paramValue">
          <el-select
            v-model="param.paramValue"
            style="width: 400px"
            :placeholder="translate('placechooseSCard')"
          >
            <el-option
              v-for="item in activeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item
        v-if="param.configId == '11'"
        :label="translate('textContent')"
        prop="content"
      >
        <quill-editor
          ref="myTextEditor"
          v-model="param.content"
          :placeholder="translate('qsrnr')"
          class="myQuillEditor"
          :options="quillOption"
        />
        <!-- <WangEditor
          :value="param.content"
          @input="(e) => $set(param, 'content', e)"
        /> -->
      </el-form-item>
      <el-form-item :label="translate('sort')" prop="sort">
        <el-input
          v-model="param.sort"
          style="width: 400px"
          type="number"
          :placeholder="translate('sortPlace')"
          maxlength="50"
        />
      </el-form-item>
      <div class="line-style" />
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
          >{{ translate("tj") }}</el-button
        >
      </el-form-item></el-form
    >
  </div>
</template>

<script>
import request from "@/utils/request";
import {
  uploadFile,
  bannerSave,
  bannerUpdate,
  bannerDetail,
  venueList,
  bannerConfigInfo,
} from "@/api";
// import WangEditor from '@/components/quillOption'
import { quillEditor } from "vue-quill-editor";
import quillConfig from "@/api/sc.js";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import Cropper from "@/components/cropper";
export default {
  name: "HomePageEdit",
  components: {
    Cropper,
    quillEditor,
  },
  data() {
    return {
      quillOption: quillConfig,
      subLoading: false,
      shopId: localStorage.getItem("shopId"),
      uploadFileUrl: uploadFile,
      optionImg: "",
      fileinfo: {},
      dialogCropperVisible: false,
      uploadData: {
        folder: "KNOWLEDGE_IMG",
        type: "",
      },
      venueList: [],
      title: "",
      adTypes: [
        // 0:首页banner，1:新人广告; 广告类型 ,
        { id: "0", name: this.translate("venueHomeBanner") },
        { id: "1", name: this.translate("xrgg") },
        // { id: '2', name: '首页悬浮广告' },
        { id: "3", name: this.translate("splb") },
        { id: "4", name: this.translate("shsylb") },
        { id: "5", name: this.translate("syjlbt") },
      ],
      queryPath: "",
      param: {
        venueIds: [],
      },
      types: [],
      activeList: [],
      rules: {
        imageFullPath: [
          {
            required: true,
            message: this.translate("adverPicPlace"),
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: this.translate("textContentPlace"),
            trigger: "change",
          },
        ],
        title: [
          {
            required: true,
            message: this.translate("titlePlace"),
            trigger: "blur",
          },
        ],
        videoNumberId: [
          {
            required: true,
            message: this.translate("videoNumIdP"),
            trigger: "blur",
          },
        ],
        videoId: [
          {
            required: true,
            message: this.translate("videoIdP"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: this.translate("adverTypesPlace"),
            trigger: "change",
          },
        ],
        paramValue: [
          {
            required: true,
            message: this.translate("placechooseSCard"),
            trigger: "change",
          },
        ],
        info: [
          {
            required: true,
            message: this.translate("contentPlace"),
            trigger: "blur",
          },
        ],
        sort: [
          {
            pattern: /^\+?[1-9][0-9]*$/,
            message: this.translate("sortPlace"),
            trigger: "blur",
          },
        ],
        venueIds: [
          {
            required: true,
            message: this.translate("applyVenueP"),
            trigger: "change",
          },
        ],
        configId: [
          {
            required: true,
            message: this.translate("gllxP"),
            trigger: "change",
          },
        ],
        // aboutIndex: [
        //   { required: true, message: '请选择关联内容', trigger: 'change' }
        // ]
      },
      edit: false,
      cgList: [],
      id: "",
    };
  },
  mounted() {
    if (this.$route.query.id) {
      this.$route.meta.title = this.translate("homeAdverEdit");
      this.title = this.translate("homeAdverEdit");
      this.id = this.$route.query.id;
      this.edit = true;
      this.getData();
    } else {
      this.$route.meta.title = this.translate("homeAdverAdd");
      this.title = this.translate("homeAdverAdd");
      this.getConfigInfo();
    }
    venueList({
      param: {},
    })
      .then((res) => {
        if (res.errorCode !== "000000") return;
        this.venueList = res.recordList;
      })
      .catch(() => {});
  },
  methods: {
    getData() {
      bannerDetail({ param: { id: this.id } })
        .then((res) => {
          if (res.errorCode === "000000") {
            const obj = res.record;
            this.param = obj;
            sessionStorage.setItem("venueId", res.record.venueIds[0]);
            bannerConfigInfo({ param: {} })
              .then((resb) => {
                if (resb.errorCode === "000000") {
                  this.types = resb.record;
                  this.types.forEach((item) => {
                    if (item.id === this.param.configId) {
                      this.activeName = item.nameKey;
                      this.queryPath = item.queryPath;
                      this.param.idKey = item.idKey;
                      this.activeName = item.nameKey;
                      this.param.jumpPath = item.jumpPath;
                      if (item.jumpPath) {
                        this.getActive();
                      }
                    }
                  });
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getConfigInfo() {
      bannerConfigInfo({})
        .then((res) => {
          if (res.errorCode === "000000") {
            this.types = res.record;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    selectVenue(v) {
      this.activeList = [];
      this.$set(this.param, "paramValue", "");
      this.param.paramName = "";
      this.$set(this.param, "aboutIndex", "");
      sessionStorage.setItem("venueId", v);
      // if (this.param.configId == 8) {
      //   SpeailCardList({ param: { status: 0 }}).then(res => {
      //     this.activeList = res.recordList
      //   })
      // }

      if (this.param.jumpPath) {
        this.getActive();
      }
    },
    fwbChange(e) {
      this.$set(this.param, "content", e);
    },
    selectType(id) {
      this.activeList = [];
      this.$set(this.param, "paramValue", "");
      this.param.paramName = "";
      this.$set(this.param, "venueIds", []);
      const item = this.types.find((item) => item.id === id);
      this.activeName = item.nameKey;
      this.param.idKey = item.idKey;
      this.param.jumpPath = item.jumpPath;
      this.queryPath = item.queryPath;
      this.$refs.ruleForm.clearValidate();
      // if (!this.param.venueId) {
      //   this.$message.error(this.translate('placechooseVenue'))
      //   return
      // }
      if (item.jumpPath && id === 8) {
        this.getActive();
      }
      if (id === 10) {
        this.getActive();
      }
      if (item.jumpPath && this.param.venueIds.length === 1) {
        this.getActive();
      }
    },
    getActive() {
      if (
        !(this.param && this.param.venueIds && this.param.venueIds.length > 0)
      ) {
        return false;
      }
      request({
        url: `/do?c=${this.queryPath}`,
        method: "POST",
        data: {
          param: {
            venueId: this.param.venueIds.join(","),
            stadiumId: this.param.venueIds.join(","),
            courseStatus: "2",
            status: "1",
            saleType: this.param.configId === 10 ? "0" : "",
            type: "1",
            flag: this.param.configId === 6 ? "2" : "1",
            saleStatus: "1",
          },
        },
      })
        .then((res) => {
          if (res.errorCode === "000000") {
            this.activeList = res.recordList;
            if (this.queryPath === "411006") {
              const now = +new Date().getTime();
              this.activeList = res.recordList.filter((item) => {
                const end = +new Date(item.saleDateEnd).getTime();
                return end > now;
              });
            }
            this.activeList.forEach((item, index) => {
              if (item[this.param.idKey] === this.param.paramValue) {
                // this.param.aboutIndex = index
                this.$set(this.param, "aboutIndex", index);
              }
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    selectContent(index) {
      // console.log(index);
      const item = this.activeList[index];
      // console.log(item);
      this.param.paramValue = item[this.param.idKey] ?? item.id;
      this.param.paramName = item[this.activeName] ?? item.name;
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      if (this.param.type !== "1") return;
      if (res.success) {
        this.$set(this.param, "imageFullPath", res.showUrl);
        this.$set(this.param, "pathUrl", res.insertUrl);
        this.$refs.ruleForm.clearValidate();
      } else {
        this.$message.error(res.msg || this.translate("scsb"));
      }
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, "imageFullPath", config.showUrl);
        this.$set(this.param, "pathUrl", config.insertUrl);
        this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false;
      } else {
        this.$message.error(config.msg || this.translate("scsb"));
        this.$refs.form.clearValidate();
        this.dialogCropperVisible = false;
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false;
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      if (this.param.type === "1") return;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw);
        this.fileinfo = file.raw;
        this.dialogCropperVisible = true;
      });
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      // this.$set(this.param, 'img2', '')
      this.$set(this.param, "pathUrl", "");
      this.$set(this.param, "imageFullPath", "");
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = { ...this.param };
          // if (param.configId !== 5) {
          //   param.venueIds = [param.venueId]
          // }
          if (
            param.configId !== 5 &&
            param.configId !== 11 &&
            param.venueIds.length === 0
          ) {
            this.$message.error(this.translate("placechooseVenue"));
            return;
          }
          this.subLoading = true;
          if (this.edit) {
            bannerUpdate({
              param,
            })
              .then((res) => {
                this.subLoading = false;
                if (res.errorCode === "000000") {
                  this.$message.success(this.translate("tjScs"));
                  this.$router.replace(`/options/homePageList?renovate=1`);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            param.status = "1";
            bannerSave({
              param,
            })
              .then((res) => {
                this.subLoading = false;
                if (res.errorCode === "000000") {
                  this.$message.success(this.translate("tjScs"));
                  this.$router.replace(`/options/homePageList?renovate=1`);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
